/*
 * Created on Oct 30, 2003
 */
package com.unash.server.z3950Server;


/**
 * @author Ashwini Gokhale
 */

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import com.unash.util.AsnUtil;
import com.unash.z3950.pdu.Request;
import com.unash.z3950.pdu.Z3950BerDecoder;
import com.unash.z3950.pdu.Z3950Decoder;


public class Z3950Connection implements Runnable{
	
	private Socket clientSocket;
	private InputStream iStream;
	private OutputStream oStream;
	
	private Thread runner = null;
	Z3950Association z3950Association;
	
	public Z3950Connection(Socket s) throws IOException{
		clientSocket = s;
		iStream = clientSocket.getInputStream();
		oStream = clientSocket.getOutputStream();
			
	}//Z3950Connection(Socket s)
	
	/**
	 * @return
	 */
	public Z3950Association getZ3950Association() {
		return z3950Association;
	}


	
	public void start(){
		if(runner == null){
			runner = new Thread(this,"");
			runner.start();
		}//if
	}//start

	public void run(){
		try{
			System.out.println("Processing request");
			AsnUtil.TagInfo tagInfo = null;
			Z3950Decoder decoder = new Z3950BerDecoder();		
			while(true){
					Request objRequest = decoder.decodeRequest(iStream);
					Z3950Operation zOperation = new Z3950Operation(this,objRequest);
					zOperation.start();
					
				//when Z3950 connection is terminated.
				if(false){			
					iStream.close();
					oStream.close();
					clientSocket.close();
				}//if
			}//while
		}catch(Exception e){
			System.out.println(e);
			e.printStackTrace();
		}//catch
	}//run
	
	
	public void write(byte[] value)throws IOException,Exception{
		oStream.write(value);
	}//write
	
	
	public ByteArrayInputStream read(AsnUtil.TagInfo tagInfo) throws Exception{
		tagInfo = AsnUtil.decodeTag(iStream);
		int length = AsnUtil.decodeLength(iStream);
		byte[] request = AsnUtil.readNBytes(iStream,length);
		ByteArrayInputStream bis = new ByteArrayInputStream(request);
		return bis;
	}//read
	
	public void updateAssociation(){
		
	}//updateAssociation
	
}